package com.mxchip.livestarmobile.mobile.ui.contact

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.mxchip.livestarmobile.mobile.ContactDetailActivity
import com.mxchip.livestarmobile.R
import com.mxchip.livestarmobile.mobile.db.entity.Contact
import kotlinx.android.synthetic.main.fragment_contact.*

class ContactFragment : Fragment() {

    private val contactViewModel by activityViewModels<ContactViewModel>()

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?, savedInstanceState: Bundle?): View? {

        return inflater.inflate(R.layout.fragment_contact, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = ContactRecyclerAdapter(onClickListener = this::openContactDetailActivity)

        contactViewModel.contactFilterList().observe(viewLifecycleOwner, Observer { list ->

            Log.e("ContactFragment", "list size: " + list.size)

            val adapter = recyclerView.adapter

            if (adapter is ContactRecyclerAdapter) {
                adapter.data = list
                adapter.notifyDataSetChanged()
            }

        })


        imageButton.setOnClickListener {
            val action = ContactFragmentDirections.actionNavigationContactToAddMemberFragment()
            findNavController().navigate(action)
        }
    }

    private fun openContactDetailActivity(view: View, contact: Contact) {
        val intent = Intent(context, ContactDetailActivity::class.java)
        intent.putExtra("contactId", contact.uid)
        startActivity(intent)
    }


}